package com.cheng.commonutlis.mvvm.base;

import android.os.Bundle;
import android.view.ViewGroup;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProviders;

import com.cheng.commonlibrary.activity.CommonActivity;
import com.cheng.commonlibrary.system.SystemBarUtils;
import com.cheng.commonutlis.R;

import java.lang.reflect.ParameterizedType;

public abstract class BaseActivity<VM extends ViewModel, VDB extends ViewDataBinding> extends CommonActivity {

    protected VM mViewModel;
    protected VDB binding;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (loadSystemBarColor() != -1) {
            updateStatusBar(getResources().getColor(loadSystemBarColor()));
        }
        initModel();
    }

    public void initModel() {
        binding = DataBindingUtil.setContentView(this, loadLayoutResId());
        binding.setLifecycleOwner(this);
        //获得泛型参数的实际类型
        Class<VM> vmClass = (Class<VM>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            mViewModel = ViewModelProviders.of(this).get(vmClass);

        afterCreate();
    }

    protected abstract void afterCreate();


    /**
     * 是否设置系统栏颜色
     */
    @ColorRes
    protected int loadSystemBarColor() {
        return -1;
    }

    public void updateStatusBar(@ColorInt int color) {
        updateStatusBar(color, true, true);
    }

    public void updateStatusBar(@ColorInt int color, boolean isFits, boolean isBlack) {
        updateStatusBar(true, false/*ScreenUtils.hasNavigationBar(this)*/,
                isFits, isBlack, color, getResources().getColor(R.color.colorPrimary));
    }

    /**
     * 更改状态栏颜色
     */
    public void updateStatusBar(boolean isStatusBar, boolean isNavBar,
                                boolean isFits, boolean isBlack,
                                @ColorInt int color, @ColorInt int defColor) {
        ViewGroup group = getActivity().findViewById(android.R.id.content);
        if (group.getChildCount() < 1) {
            return;
        }
        SystemBarUtils.setSysbarColor(getWindow(), group.getChildAt(0),
                isStatusBar, isNavBar, isFits, isBlack, color, defColor);
    }
}
